package com.hsc.www.selfLock;

import com.hsc.www.selfLock.key.KeyGenerator;
import com.hsc.www.selfLock.store.Cache;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Method;

public class SelfLockMethodInterceptor implements MethodInterceptor {

    private Cache cache;

    private KeyGenerator keyGenerator;

    public SelfLockMethodInterceptor(Cache cache) {
        this.cache = cache;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("SelfLock拦截前");
        //获取指定方法
        Method method = ClassUtils.getMostSpecificMethod(invocation.getMethod(), AopUtils.getTargetClass(invocation.getThis()));
        //获取方法上注
        SelfLock selfLock = AnnotatedElementUtils.findMergedAnnotation(method, SelfLock.class);
        String key = keyGenerator.generate(selfLock, invocation.getThis(), invocation.getMethod(), invocation.getArguments());
        boolean isExist = cache.get(key, Object.class) == null ? false : true;
        if (isExist) {
            throw new RuntimeException("某某已经存在……");
        }
        try {
            cache.put(key, 1);
            return invocation.proceed();
        } catch (Exception e) {
            throw e;
        } finally {
            cache.remove(key);
            System.out.println("SelfLock拦截后");
        }
    }


}